package com.wzj.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.oss.service.FileService;
import com.wzj.yygh.oss.utils.ConstantProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private ConstantProperties constantProperties;
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = constantProperties.getEndpoint();
        String accessKeyId = constantProperties.getKeyId();
        String accessKeySecret = constantProperties.getKeySecret();
        String bucketName = constantProperties.getBucketName();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            boolean exist = ossClient.doesBucketExist(bucketName);
            if (!exist) {
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            StringBuilder fileName = new StringBuilder();
            fileName.append(file.getOriginalFilename());
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName.append(uuid).append(fileName);

            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName.append(timeUrl).append("/").append(fileName);

            //调用方法实现上传
            // 1.jpg    /a/b/1.jpg
            ossClient.putObject(bucketName, String.valueOf(fileName), inputStream);
            //上传之后文件路径
           // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            //返回
            return "https://"+bucketName+"."+endpoint+"/"+fileName;
        } catch (IOException e) {
            throw new YyghException(ResultCode.ERROR,"文件上传失败",e);
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
    }
}
